// document.write("<script language=javascript src='DSWebsocketEngine.js'></script>");

function web_DSConnectionCheck() {
  ConnectionTest();
  Invoke(arguments);
}
function web_DSInitService() {
  InitService('127.0.0.1:7999');
}
function web_DSisConnectOn() {
  return ds_isConnectOn();
}
function web_Wait(timeout, cb) {
  Sleep(timeout, cb);
}
function web_DSQuitSvc() {
  Invoke(arguments);
}

/////////////////////////////////

function web_DSEnumPrinter() {
  Invoke(arguments);
}
function web_DSOpenPrinter() {
  Invoke(arguments);
}
function web_DSGetPrinterModel() {
  Invoke(arguments);
}
function web_DSClosePrinter() {
  Invoke(arguments);
}
function web_DSGetPrinterSN() {
  Invoke(arguments);
}
function web_DSPrintTraceInfo() {
  Invoke(arguments);
}
function web_DSDownloadFile() {
  Invoke(arguments);
}
function web_DSPrintIssuePermit() {
  Invoke(arguments);
}
function web_DSZPLPrintText() {
  Invoke(arguments);
}
function web_DSZPLPrintCode128() {
  Invoke(arguments);
}
function web_DSZPLSetFont() {
  Invoke(arguments);
}
function web_DSZPLBarCode128() {
  Invoke(arguments);
}
function web_DSZPLPrintQrCode() {
  Invoke(arguments);
}
function web_DSZPLPrintImage() {
  Invoke(arguments);
}
function web_DSZPLPrintLine() {
  Invoke(arguments);
}
function web_DSZPLSetPageLength() {
  Invoke(arguments);
}
function web_DSPrintQrCodeForLibrary() {
  Invoke(arguments);
}

function web_DAS_RFIDTag_Write_EPCID() {
  Invoke(arguments);
}
function web_DAS_RFIDTag_Write_EPCIDA() {
  Invoke(arguments);
}
function web_DAS_RFIDTag_Read_TIDEPCID() {
  Invoke(arguments);
}
function web_DSZPLPrintQrCodeExA() {
  Invoke(arguments);
}
function web_DSZPLPrintCode128A() {
  Invoke(arguments);
}
function web_DSZPLPrintTextEx() {
  Invoke(arguments);
}
function web_DAS_RFIDTag_SetReadPower() {
  Invoke(arguments);
}
function web_DAS_RFIDTag_FetchReadPower() {
  Invoke(arguments);
}
function web_DAS_RFIDTag_SetWritePower() {
  Invoke(arguments);
}
function web_DAS_RFIDTag_FetchWritePower() {
  Invoke(arguments);
}
function web_DAS_RFID_TagForward() {
  Invoke(arguments);
}
function web_DAS_RFID_TagBackward() {
  Invoke(arguments);
}
function web_DAS_RFID_Position_Adjustment() {
  Invoke(arguments);
}
function web_DAS_RFID_Automatic_Location() {
  Invoke(arguments);
}
function web_DSZPLRotation() {
  Invoke(arguments);
}
function web_DSZPLSetCutter() {
  Invoke(arguments);
}
function web_DSGetMFG() {
  Invoke(arguments);
}
///////////////////////////////
function web_DAS_RFIDTag_Read_EPCIDA() {
  Invoke(arguments);
}
function web_DAS_RFIDTag_Read_TIDIDA() {
  Invoke(arguments);
}
//////////////////////////////////////
function web_DSZPLPrintImageExA_SizeScalable() {
  Invoke(arguments);
}

function web_DSGetStarPrint() {
  Invoke(arguments);
}
function web_DSGetReadEPC() {
  Invoke(arguments);
}

//////////////////////////////////////
function test_fun() {
  Invoke('test_fun', 1, 2, 3, [1, 2], arguments[0]);
}

function DSInitService() {
  web_DSInitService();
}

function DSLaunchApp() {
  web_DSLaunchApp();
}

function web_DSLaunchApp() {
  var a = document.createElement('a');
  //a.href="dsdraw:none";
  a.href = 'a1:none';
  //a.href="www.baidu.com";
  //a.display="none";
  document.body.appendChild(a);
  a.click();

  var c = arguments.length;
  if (c > 0) {
    if (typeof arguments[0] == 'object') {
      var cb = arguments[0];
      Sleep(5000, cb);
    }
  }
}

function web_DSNewLaunchApp() {
  var e = document.createElement('a');
  var reg = RegExp('^[A-Za-z0-9]+(://){1}$');
  if (arguments[0] && typeof arguments[0] == 'string' && reg.test(arguments[0]))
    e.href = arguments[0];
  else e.href = 'DSWebPrtSvc://'; //alert("error");
  e.innerHTML = '';
  document.getElementsByTagName('body')[0].appendChild(e);

  var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
  var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1; //判断是否IE<11浏览器
  var isEdge = userAgent.indexOf('Edge') > -1 && !isIE; //判断是否IE的Edge浏览器
  var isIE11 = userAgent.indexOf('Trident') > -1 && userAgent.indexOf('rv:11.0') > -1;
  var myHref;
  if (isIE || isIE11) {
    //window.history.back(-1);
    myHref = window.location.href;
  }
  e.click();
  if (isIE || isIE11) {
    //window.history.back(-1);
    var textHref = window.location.href;
    if (myHref != window.location.href) window.history.back(-1);
  }

  document.getElementsByTagName('body')[0].removeChild(e);
}

function web_DSPrtEngineStartup1() {
  DSInitService();
  web_Wait(1000, function (res) {
    if (!res) {
      alert('服务未启动，请启动服务；');
      DSLaunchApp();
      web_Wait(15000, function (res) {
        if (!res) output('启动服务失败');
        else output('启动服务成功');
      });
    } else output('启动服务成功');
  });
}

function web_DSPrtEngineStartup(callBackFun, ifOpen) {
  if ('function' != typeof arguments[0]) return;
  DSInitService();

  web_Wait(1000, function (res) {
    if (!res) {
      callBackFun(-1);
      if (true == ifOpen) web_DSNewLaunchApp('DSWebPrtSvc://');
      web_Wait(15000, callBackFun);
    } else callBackFun(true);
  });
}

////////////////////////////////////////得实网页模板编辑 websocket 通讯组件，请勿擅自修改本文件内容！！！////////////////////////////////////////////////////

var ds_res = '';
var WebsocketSever = '127.0.0.1:7999';
var t1 = null; //废除
var t2 = null; //废除
var t3 = null;
var lastHeartBeat = null; //废除
var flag = 0; //当前调用状态：0：未调用，1：调用中（等待），2：成功调用，3：超时
var flagConment = null; //当前状态的任务信息
var currentJob = null;
var reqQueue = new Array(); //请求队列
var processQueue = new Array(); //处理队列
var resQueue = new Array(); //结果队列
var seq = 0; //包序列号
var timebase = 0;
var StatusMachineSpeed = 1; //废除
var hooker_packinfo = null;
var g_invoke_result = null;
var iterator = null;
var StatusMachine_running = false;
function closeMe() {
  window.opener = null;
  window.open('', '_self');
  window.close();
}
function StatusMachine() {
  if (StatusMachine_running) return;
  StatusMachine_running = true;
  if (0 == flag) {
    ds_res = '';
    if (reqQueue.length != 0) {
      currentJob = reqQueue.pop();
      processQueue.unshift(currentJob);
      var callback = currentJob.CALLBACK[0];
      delete currentJob['CALLBACK']; //服务器不需要回调函数信息，删除之
      ds_sendToPrinter(JSON.stringify(currentJob));
      currentJob.CALLBACK = new Array();
      currentJob.CALLBACK[0] = callback;
      timebase = Date.now();
      flag = 1;
    }
  } else if (1 == flag) {
    var packtype = currentJob.PackType;
    var overtime = packtype == 10 ? 1500 : packtype == 11 ? 60000 : 1000;
    if (Date.now() - timebase > overtime) flag = 3;
    if (ds_res != '') flag = 2;
    var o = { RtnCode: -1002, Remarks: currentJob.ReqInfo.FunName, SEQ: currentJob.SEQ };
    flagConment = o;
  } else if (2 == flag) {
    flag = 0;
    var o = eval('(' + ds_res + ')');
    resQueue.unshift(o);
    for (var i = 0; i < processQueue.length; i++) {
      var obj = processQueue[i];
      if (obj.ReqInfo.FunName == o.Remarks && obj.SEQ == o.SEQ) {
        processQueue.splice(i, 1);
        break;
      }
    }
    currentJob = null;
    flagConment = o;
    var callback = obj.CALLBACK[0];
    if (callback != null) {
      window.setTimeout(callback(o), 1);
    }
  } else if (3 == flag) {
    flag = 0;
    var obj = null;
    var o = { RtnCode: -1003, Remarks: currentJob.ReqInfo.FunName, SEQ: currentJob.SEQ };
    for (var i = 0; i < processQueue.length; i++) {
      var obj = processQueue[i];
      if (obj.ReqInfo.FunName == o.Remarks && obj.SEQ == o.SEQ) {
        obj = processQueue.splice(i, 1)[0];
        break;
      }
    }
    //resQueue.unshift(o);
    currentJob = null;
    flagConment = o;
    try {
      var callback = obj.CALLBACK[0];
      if (callback != null) {
        window.setTimeout(callback(o), 1);
      }
    } catch (e) {}
  }
  StatusMachine_running = false;
}

function ConnectionTest() {
  hooker_packinfo = {
    PackType: 12,
    ReqInfo: { FunName: 'InvalidFunction', Parameters: [] },
    SEQ: seq,
    CALLBACK: [],
  };
}
var websocket = null;
var FirstTime = true;
var serviceRunning = false;
var t_statusmachine = null;
var t_connect = null;
var s_requestOk = false;

function InitService() {
  s_requestOk = false;
  serviceRunning = false;
  if (FirstTime) {
    WebsocketSever = arguments[0];
    FirstTime = false;
    t_statusmachine = window.setInterval(StatusMachine, 5);
  }
  var pt = 'ws://';
  try {
    if ('WebSocket' in window) {
      websocket = new WebSocket(pt + WebsocketSever);
    } else if ('MozWebSocket' in window) {
      websocket = new MozWebSocket(pt + WebsocketSever);
    } else {
      alert('当前浏览器不支持WebSocket');
      //closeMe();
      return;
    }
  } catch (e) {
    //alert("创建WebSocket失败");
    return false;
  }

  s_requestOk = true;

  websocket.onopen = function (evt) {
    if (t_connect != null) {
      window.clearTimeout(t_connect);
      t_connect = null;
    }
    serviceRunning = true;
    StatusMachine_running = false;

    KeepAlive(1);
  };

  websocket.onmessage = function (evt) {
    var o = msgCheck(evt.data)
      ? eval('(' + evt.data + ')')
      : Object.create(Object.prototype);
    if (o.hasOwnProperty('Remarks')) {
      var str = o.Remarks;
      if (str != 'KeepAlive') {
        console.log('websocket onmessage:' + evt.data);
      }
      ds_res = evt.data;
    }
  };

  websocket.onerror = function (evt) {
    //console.log("websocket err!");
    //alert("websocket.onerror");
    websocket.close();
    if (currentJob != null) {
      var s = {
        RtnCode: -1004,
        Remarks: currentJob.ReqInfo.FunName,
        SEQ: currentJob.SEQ,
      };
      ds_res = JSON.stringify(s);
    }

    serviceRunning = false;
    KeepAlive(0);
    websocket = null;
    //t_connect = window.setTimeout(InitService(WebsocketSever),1000);
  };

  websocket.onclose = function () {
    //console.log("websocket close!");
    //websocket = null;
    //alert("websocket close!");
    serviceRunning = false;
    KeepAlive(0);
    websocket = null;
    t_connect = window.setTimeout(InitService(WebsocketSever), 1000);
  };
}

function msgCheck(str) {
  if (typeof str == 'string') {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }
}

function KeepAlive(s) {
  if (s == 1) {
    if (t3 != null) window.clearInterval(t3);
    t3 = window.setInterval(__KeepAlive, 3000);
  } else if (s == 0) {
    if (t3 != null) window.clearInterval(t3);
  }
  function __KeepAlive() {
    hooker_packinfo = {
      PackType: 13,
      ReqInfo: { FunName: 'KeepAlive', Parameters: [] },
      SEQ: seq,
      CALLBACK: [],
    };
    Invoke('KeepAlive');
  }
}

function Invoke() {
  if (arguments.length == 0) {
    //console.log("The paramenter list can not be empty!");return;
  }

  var callback = null;
  var funname = '';
  var data =
    hooker_packinfo == null
      ? {
          PackType: 11,
          ReqInfo: { FunName: 'InvalidFunction', Parameters: [] },
          SEQ: seq,
          CALLBACK: [],
        }
      : hooker_packinfo;
  hooker_packinfo = null;
  var parlen = 0;
  var obj = null;
  if (typeof arguments[0] != 'object') {
    funname = arguments[0] + '';
    obj = new Array();
    for (var i = 1; i < arguments.length; i++) obj[i - 1] = arguments[i];
  } else {
    obj = arguments[0];
    funname = obj.callee + '';
    funname = funname.substring(funname.indexOf(' ') + 1, funname.indexOf('('));
  }
  data.ReqInfo.FunName = funname;
  parlen = obj.length;
  if (parlen > 0) {
    var tempCallback = obj[parlen - 1];
    if (typeof tempCallback == 'function') {
      callback = obj[parlen - 1];
      parlen = parlen - 1;
    }
    for (var i = 0; i < parlen; i++) {
      data.ReqInfo.Parameters[i] = obj[i];
    }
  }

  data.SEQ = seq;
  seq++;
  //if(data.ReqInfo.FunName=="web_DSEnumPrinter")alert("xcvbbbnn"+JSON.stringify(currentJob));
  data.CALLBACK[0] = callback;
  reqQueue.unshift(data);
}

function ds_sendToPrinter(sdata) {
  var obj = JSON.parse(sdata);
  if (JSON.parse(sdata).PackType != 13) {
    console.log('websocket send:' + sdata);
  }
  if (serviceRunning && t_statusmachine != null) websocket.send(sdata);
  else {
    var s = { RtnCode: -1005, Remarks: obj.ReqInfo.FunName, SEQ: obj.SEQ };
    ds_res = JSON.stringify(s);
  }
}

function ds_isConnectOn() {
  return serviceRunning;
}

function Sleep(timeout, cb) {
  var T = Date.now();
  innerSleep();
  function innerSleep() {
    if (serviceRunning) {
      cb(serviceRunning);
      return;
    }
    if (Date.now() - T < timeout) {
      window.setTimeout(innerSleep, 100);
    } else cb(serviceRunning);
  }
}
